package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"proxy/api"
	mylog "proxy/log"
	"sync"
)

const (
	kTsxIdMax = 100
)

var log = mylog.NewOverlog("proxy", "backend")

func main() {

	client := &Client{
		proxyUrl: url.URL{
			Scheme: "http",
			Host:   ":2018",
			Path:   "/rtc",
		},
		rtcIds: make([]string, 0),
	}

	cmd := os.Args[1]
	switch cmd {
	case "create":
		client.CreateRtc()
	case "terminate":
		rtcId := os.Args[2]
		client.TerminateRtc(rtcId)
	}
}

type Client struct {
	mu       sync.Mutex
	proxyUrl url.URL
	tsxId    int
	rtcIds   []string
}

func (c *Client) CreateRtc() {

	call := api.Request{
		Op:    api.OpCall,
		TsxId: c.getTsxId(),
		CtxId: "test-conf",
	}

	httpRsp, err := http.Post(c.proxyUrl.String(), "application/json", bytes.NewReader(call.Encode()))
	if err != nil {
		log.Panicf("could not send initC: %s", err)
	}

	body, err := ioutil.ReadAll(httpRsp.Body)
	if err != nil {
		log.Panicf("could not read response body, error: %s", err)
	}

	log.Printf("got %d %s", httpRsp.StatusCode, body)

	rsp, err := api.ParseResponse(body)
	if err != nil {
		log.Panic("could not decode response body")
	}

	rtcId := rsp.RtcId
	status := rsp.Status

	log.Infof("created rtc |%s| status |%d|", rtcId, status)

	c.rtcIds = append(c.rtcIds, rtcId)
}

func (c *Client) getTsxId() string {
	c.mu.Lock()
	c.tsxId = (c.tsxId + 1) % kTsxIdMax
	c.mu.Unlock()

	return fmt.Sprintf("%d", c.tsxId)
}

func (c *Client) TerminateRtc(rtcId string) {

	term := api.Request{
		Op:    api.OpTerminate,
		TsxId: c.getTsxId(),
		CtxId: "test-conf",
		RtcId: rtcId,
	}

	httpRsp, err := http.Post(c.proxyUrl.String(), "application/json", bytes.NewReader(term.Encode()))
	if err != nil {
		log.Panicf("could not send termC: %s", err)
	}

	body, err := ioutil.ReadAll(httpRsp.Body)
	if err != nil {
		log.Panicf("could not read termC response, error: %s", err)
	}

	log.Printf("got %d %s", httpRsp.StatusCode, body)

	rsp, err := api.ParseResponse(body)
	if err != nil {
		log.Panic("could not decode response body")
	}

	log.Infof("terminated rtc |%s| status |%d|", rtcId, rsp.Status)
}

type Rtc struct {
	Id string
}
